package com.joven.shelltest.utils;

/**
 * 莱文斯坦距离 <=2 即为相似
 * @author w6168
 */
public class LevenshteinDistance {

    public static int computeLevenshteinDistance(String str1, String str2) {
        int len1 = str1.length();
        int len2 = str2.length();

        // 创建一个矩阵
        int[][] dp = new int[len1 + 1][len2 + 1];

        // 初始化矩阵的第一行和第一列
        for (int i = 0; i <= len1; i++) {
            dp[i][0] = i;
        }
        for (int j = 0; j <= len2; j++) {
            dp[0][j] = j;
        }

        // 遍历并填充矩阵
        for (int i = 1; i <= len1; i++) {
            for (int j = 1; j <= len2; j++) {
                int cost = (str1.charAt(i - 1) == str2.charAt(j - 1)) ? 0 : 1;

                dp[i][j] = Math.min(Math.min(dp[i - 1][j] + 1,      // 删除
                                dp[i][j - 1] + 1),     // 插入
                        dp[i - 1][j - 1] + cost);       // 替换
            }
        }

        return dp[len1][len2];
    }

    public static void main(String[] args) {
        String str1 = "15157006283";
        String str2 = "15257006284";
        System.out.println("Levenshtein Distance: " + computeLevenshteinDistance(str1, str2));
    }
}

